import { Component, Vue, Inject, Prop, Watch, Ref } from 'vue-property-decorator';
import { numeric, required, minLength, maxLength } from 'vuelidate/lib/validators';
import moment from 'moment';
import { DATE_TIME_LONG_FORMAT } from '@/shared/date/filters';

import CommonTableFieldService from '../../modelConfig//common-table-field/common-table-field.service';
import { ICommonTableField } from '@/shared/model/modelConfig/common-table-field.model';

import CommonTableRelationshipService from '../../modelConfig//common-table-relationship/common-table-relationship.service';
import { ICommonTableRelationship } from '@/shared/model/modelConfig/common-table-relationship.model';

import UserService from '@/shared/service/user.service';

import BusinessTypeService from '../../settings//business-type/business-type.service';
import { IBusinessType } from '@/shared/model/settings/business-type.model';

import { ICommonTable, CommonTable } from '@/shared/model/modelConfig/common-table.model';
import CommonTableService from './common-table.service';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { quillEditor } from 'vue-quill-editor';
import { UPLOAD_IMAGE_URL } from '@/constants';
import CommonTableFieldComponent from '../../modelConfig//common-table-field/common-table-field.vue';
import CommonTableRelationshipComponent from '../../modelConfig//common-table-relationship/common-table-relationship.vue';

const validations: any = {
  commonTable: {
    id: {},
    name: {
      required,
      maxLength: maxLength(80),
    },
    entityName: {
      required,
      maxLength: maxLength(80),
    },
    tableName: {
      required,
      maxLength: maxLength(80),
    },
    system: {},
    clazzName: {
      required,
      maxLength: maxLength(80),
    },
    generated: {},
    creatAt: {},
    generateAt: {},
    generateClassAt: {},
    description: {
      maxLength: maxLength(200),
    },
    treeTable: {},
    baseTableId: {},
    recordActionWidth: {},
    listConfig: {},
    formConfig: {},
    editInModal: {},
    searchForm: {},
  },
};

@Component({
  validations,
  components: {
    'jhi-quill-editor': quillEditor,
    'jhi-common-table-field': CommonTableFieldComponent,
    'jhi-common-table-relationship': CommonTableRelationshipComponent,
  },
})
export default class CommonTableUpdateTemplate extends Vue {
  // jhipster-pro-please-regenerate-this-file 如果您修改了此文件，并且不希望重新生成代码时被覆盖，请删除本行！！!

  @Inject('commonTableService') private commonTableService: () => CommonTableService;
  public commonTable: ICommonTable = new CommonTable();

  @Inject('commonTableFieldService') private commonTableFieldService: () => CommonTableFieldService;

  public commonTableFields: ICommonTableField[] = [];

  @Inject('commonTableRelationshipService') private commonTableRelationshipService: () => CommonTableRelationshipService;

  public commonTableRelationships: ICommonTableRelationship[] = [];

  public commonTables: ICommonTable[] = [];

  @Inject('userService') private userService: () => UserService;

  public users: Array<any> = [];

  @Inject('businessTypeService') private businessTypeService: () => BusinessTypeService;

  public businessTypes: IBusinessType[] = [];
  public isSaving = false;
  public loading = false;
  @Ref('updateForm') readonly updateForm: any;
  public formJsonData = {
    list: [],
    config: {
      layout: 'horizontal',
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      hideRequiredMark: false,
      customStyle: '',
    },
  };
  public dataFormContent = [];
  public dataContent = [];
  public commonTableId = null;

  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.initRelationships();
      if (to.params.commonTableId) {
        vm.retrieveCommonTable(to.params.commonTableId);
      }
    });
  }
  created(): void {
    this.initRelationships();
  }

  public mounted(): void {}

  public save(): void {
    this.updateForm
      .getData()
      .then(values => {
        Object.assign(this.commonTable, values);
        this.isSaving = true;
        if (this.commonTable.id) {
          this.commonTableService()
            .update(this.commonTable)
            .then(param => {
              this.isSaving = false;
              const message = this.$t('jhipsterApp.modelConfigCommonTable.updated', { param: param.id }).toString();
              this.$message.info(message);
              this.$router.go(-1);
            });
        } else {
          this.commonTableService()
            .create(this.commonTable)
            .then(param => {
              this.isSaving = false;
              const message = this.$t('jhipsterApp.modelConfigCommonTable.created', { param: param.id }).toString();
              this.$message.success(message);
              this.$router.go(-1);
            });
        }
      })
      .catch(() => {
        console.log('验证未通过，获取失败');
      });
  }

  public retrieveCommonTable(commonTableId): void {
    this.commonTableService()
      .find(commonTableId)
      .then(res => {
        this.commonTable = res;
      });
  }

  public previousState(): void {
    this.$router.go(-1);
  }

  public initRelationships(): void {
    this.commonTableFieldService()
      .retrieve()
      .then(res => {
        this.commonTableFields = res.data;
      });
    this.commonTableRelationshipService()
      .retrieve()
      .then(res => {
        this.commonTableRelationships = res.data;
      });
    this.commonTableService()
      .retrieve()
      .then(res => {
        this.commonTables = res.data;
      });
    this.userService()
      .retrieve()
      .then(res => {
        this.users = res.data;
      });
    this.businessTypeService()
      .retrieve()
      .then(res => {
        this.businessTypes = res.data;
      });
  }

  // 有一问题要注意，我不能选择已经是我下级的节点做我的上级节点。
  public toTreeNode(items: any, valueFieldName: string, labelFieldName: string, currentId?: any, disabledParent: boolean = false) {
    const nzTreeNode = [];
    if (!items) {
      return nzTreeNode;
    }
    items.forEach(item => {
      let disabledChildren = false;
      const option = {
        value: item[valueFieldName],
        label: item[labelFieldName],
        disabled: disabledParent, // 树形关系中自己不能选择自己做为上级对象。
        children: undefined,
      };
      if (item[valueFieldName] === currentId) {
        option.disabled = true;
        disabledChildren = true;
      }
      if (item.children && item.children.length > 0) {
        option.children = this.toTreeNode(item.children, valueFieldName, labelFieldName, currentId, disabledChildren);
      }
      nzTreeNode.push(option);
    });
    console.log(nzTreeNode);
    return nzTreeNode;
  }
}
